<template>
  <view v-if="postExist" class="detail-container">
    <view class="post-content">
      <view class="author-info">
        <image :src="post.author.avatar" class="avatar" />
        <view class="author-meta">
          <text class="name">{{ post.author.name }}</text>
          <text class="time">{{ post.createTime | formatTime }}</text>
        </view>
        <view 
          class="collect-btn"
          @click="toggleCollect(post)"
        >
          <uni-icons 
            :type="isCollected ? 'heart-filled' : 'heart'" 
            :color="isCollected ? '#ff3b30' : '#666'"
            size="24"
          ></uni-icons>
        </view>
        <view 
          class="team-apply-btn"
          @click="showApplyForm"
        >
          <text>申请组队</text>
        </view>
      </view>
      
      <view class="post-meta">
        <text class="subject-tag">{{ post.subject }}</text>
        <view class="location-info">
          <uni-icons type="location-filled" size="16" color="#5bc0eb"></uni-icons>
          <text class="location">{{ post.location || '未选择位置' }}</text>
        </view>
      </view>
      
      <text class="content">{{ post.content }}</text>
      
      <view class="post-images" v-if="post.images && post.images.length">
        <image 
          v-for="(img, index) in post.images"
          :key="index"
          :src="img"
          mode="aspectFill"
          class="post-image"
          @click="previewImage(index)"
        />
      </view>
      
      <view class="interaction-bar">
        <view class="post-actions">
          <view class="action-item" @click="toggleLike(post)">
            <image :src="'/static/赞.png'" :class="['action-icon', isLiked ? 'active' : '']" mode="aspectFit"></image>
            <text>{{ post.likes || 0 }}</text>
          </view>
          <view class="action-item" @click="toggleCollect(post)">
            <image :src="'/static/收藏1.png'" :class="['action-icon', isCollected ? 'active' : '']" mode="aspectFit"></image>
            <text>收藏</text>
          </view>
          <view class="action-item" @click="sharePost(post)">
            <image src="/static/分享1.png" class="action-icon" mode="aspectFit"></image>
            <text>分享</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 申请组队弹窗 -->
    <view class="apply-popup" v-if="showApply">
      <view class="apply-popup-mask" @click="hideApplyForm"></view>
      <view class="apply-popup-content">
        <view class="apply-popup-header">
          <text class="apply-popup-title">申请组队</text>
          <view class="apply-popup-close" @click="hideApplyForm">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>
        <view class="apply-popup-body">
          <view class="form-item">
            <text class="form-label">联系方式</text>
            <input type="text" v-model="applyForm.contact" placeholder="请输入您的联系方式" class="form-input" />
          </view>
          <view class="form-item">
            <text class="form-label">申请说明</text>
            <textarea v-model="applyForm.message" placeholder="请简要说明您的申请理由" class="form-textarea"></textarea>
          </view>
        </view>
        <view class="apply-popup-footer">
          <button class="cancel-btn" @click="hideApplyForm">取消</button>
          <button class="submit-btn" @click="submitApply">提交申请</button>
        </view>
      </view>
    </view>
  </view>
  <view v-else class="error-container">
    <uni-icons type="info" size="60" color="#999"></uni-icons>
    <text class="error-text">该帖子已被删除</text>
  </view>
</template>

<style lang="scss" scoped>
.detail-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 30rpx;
  
  .post-content {
    background: #fff;
    border-radius: 20rpx;
    padding: 40rpx;
    box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.08);
    
    .author-info {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;
      
      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 20rpx;
        border: 2rpx solid rgba(91,192,235,0.2);
      }
      
      .author-meta {
        flex: 1;
        
        .name {
          font-size: 32rpx;
          color: #2c3e50;
          font-weight: 500;
          display: block;
        }
        
        .time {
          font-size: 24rpx;
          color: #94a3b8;
        }
      }
      
      .collect-btn {
        padding: 20rpx;
        margin: -20rpx;
        transition: all 0.2s ease;
        
        &:active {
          transform: scale(0.9);
        }
      }
      
      .team-apply-btn {
        margin-left: 20rpx;
        background: #5bc0eb;
        color: #fff;
        padding: 10rpx 20rpx;
        border-radius: 30rpx;
        font-size: 24rpx;
        transition: all 0.2s ease;
        
        &:active {
          transform: scale(0.95);
          opacity: 0.9;
        }
      }
    }
    
    .post-meta {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;
      
      .subject-tag {
        background: rgba(91,192,235,0.1);
        color: #5bc0eb;
        padding: 8rpx 20rpx;
        border-radius: 30rpx;
        font-size: 24rpx;
        margin-right: 20rpx;
      }
      
      .location-info {
        display: flex;
        align-items: center;
        color: #64748b;
        font-size: 24rpx;
        
        .location {
          margin-left: 8rpx;
        }
      }
    }
    
    .content {
      font-size: 30rpx;
      color: #334155;
      line-height: 1.8;
      margin-bottom: 30rpx;
      display: block;
    }
    
    .post-images {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20rpx;
      margin-bottom: 30rpx;
      
      .post-image {
        width: 100%;
        height: 200rpx;
        border-radius: 12rpx;
        background: #f1f5f9;
      }
    }
    
    .interaction-bar {
      margin-top: 40rpx;
      border-top: 2rpx solid #f1f5f9;
      padding-top: 30rpx;
      
      .post-actions {
        display: flex;
        justify-content: space-around;
        align-items: center;
        
        .action-item {
          display: flex;
          align-items: center;
          padding: 15rpx 30rpx;
          border-radius: 8rpx;
          transition: all 0.2s ease;
          
          &:active {
            background: #f1f5f9;
            transform: scale(0.95);
          }
          
          .action-icon {
            width: 32rpx;
            height: 32rpx;
            transition: all 0.2s ease;
            
            &.active {
              transform: scale(1.1);
            }
          }
          
          text {
            margin-left: 12rpx;
            font-size: 28rpx;
            color: #64748b;
          }
        }
      }
    }
  }
}

.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 200rpx;
  
  .error-text {
    margin-top: 30rpx;
    color: #94a3b8;
    font-size: 28rpx;
  }
}

.apply-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  
  .apply-popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.5);
  }
  
  .apply-popup-content {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    border-radius: 30rpx 30rpx 0 0;
    padding: 40rpx;
    transform: translateY(0);
    transition: transform 0.3s ease;
    
    .apply-popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      
      .apply-popup-title {
        font-size: 34rpx;
        font-weight: 500;
        color: #2c3e50;
      }
      
      .apply-popup-close {
        padding: 10rpx;
      }
    }
    
    .apply-popup-body {
      .form-item {
        margin-bottom: 30rpx;
        
        .form-label {
          display: block;
          font-size: 28rpx;
          color: #64748b;
          margin-bottom: 15rpx;
        }
        
        .form-input {
          width: 100%;
          height: 80rpx;
          background: #f8fafc;
          border-radius: 12rpx;
          padding: 0 20rpx;
          font-size: 28rpx;
          color: #334155;
          border: 2rpx solid #e2e8f0;
        }
        
        .form-textarea {
          width: 100%;
          height: 200rpx;
          background: #f8fafc;
          border-radius: 12rpx;
          padding: 20rpx;
          font-size: 28rpx;
          color: #334155;
          border: 2rpx solid #e2e8f0;
        }
      }
    }
    
    .apply-popup-footer {
      display: flex;
      justify-content: space-between;
      margin-top: 40rpx;
      
      button {
        flex: 1;
        height: 80rpx;
        border-radius: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
      }
      
      .cancel-btn {
        background: #f1f5f9;
        color: #64748b;
        margin-right: 20rpx;
      }
      
      .submit-btn {
        background: #5bc0eb;
        color: #fff;
      }
    }
  }
}
</style>

<script>
import { formatTime } from '@/utils/common.js'

export default {
  data() {
    return {
      post: {},
      postExist: true,
      isLiked: false,
      showApply: false,
      applyForm: {
        contact: '',
        message: ''
      }
    }
  },
  created() {
    // 初始化时检查点赞状态
    const likedPosts = uni.getStorageSync('likedPosts') || []
    if (this.post.id) {
      this.isLiked = likedPosts.includes(this.post.id)
    }
  },
  computed: {
    isCollected() {
      return (uni.getStorageSync('collections') || [])
        .some(item => item.id === this.post.id)
    }
  },
  onLoad(options) {
    const posts = uni.getStorageSync('posts') || []
    const foundPost = posts.find(p => p.id === Number(options.id))
    
    if (!foundPost) {
      this.postExist = false
      setTimeout(() => {
        const pages = getCurrentPages()
        if(pages.length > 1) {
          uni.navigateBack()
        } else {
          uni.reLaunch({ url: '/pages/index/index' })
        }
      }, 2000)
      return
    }
    
    this.post = foundPost
  },
  methods: {
    toggleCollect() {
      const collections = uni.getStorageSync('collections') || []
      const index = collections.findIndex(item => item.id === this.post.id)
      
      if (index === -1) {
        collections.push(this.post)
        uni.showToast({ title: '收藏成功' })
      } else {
        collections.splice(index, 1)
        uni.showToast({ title: '已取消收藏' })
      }
      
      uni.setStorageSync('collections', collections)
      uni.$emit('collection-updated')
    },
    toggleLike() {
      const likedPosts = uni.getStorageSync('likedPosts') || []
      const posts = uni.getStorageSync('posts') || []
      const postIndex = posts.findIndex(p => p.id === this.post.id)
      
      if (!this.isLiked) {
        // 添加点赞
        likedPosts.push(this.post.id)
        if (postIndex > -1) {
          posts[postIndex].likes = (posts[postIndex].likes || 0) + 1
          this.post.likes = posts[postIndex].likes
        }
        uni.showToast({ title: '点赞成功' })
      } else {
        // 取消点赞
        const index = likedPosts.indexOf(this.post.id)
        if (index > -1) {
          likedPosts.splice(index, 1)
          if (postIndex > -1) {
            posts[postIndex].likes = Math.max((posts[postIndex].likes || 1) - 1, 0)
            this.post.likes = posts[postIndex].likes
          }
        }
        uni.showToast({ title: '已取消点赞' })
      }
      
      this.isLiked = !this.isLiked
      uni.setStorageSync('likedPosts', likedPosts)
      uni.setStorageSync('posts', posts)
      uni.$emit('likes-updated')
    },
    previewImage(index) {
      uni.previewImage({
        current: index,
        urls: this.post.images
      })
    },
    // 显示申请组队表单
    showApplyForm() {
      this.showApply = true
    },
    // 隐藏申请组队表单
    hideApplyForm() {
      this.showApply = false
    },
    // 提交申请
    submitApply() {
      // 表单验证
      if (!this.applyForm.contact) {
        uni.showToast({
          title: '请填写联系方式',
          icon: 'none'
        })
        return
      }
      
      if (!this.applyForm.message) {
        uni.showToast({
          title: '请填写申请说明',
          icon: 'none'
        })
        return
      }
      
      // 保存申请信息
      const applications = uni.getStorageSync('applications') || []
      applications.push({
        id: Date.now(),
        postId: this.post.id,
        postTitle: this.post.content.substring(0, 20) + '...',
        schoolName: this.post.schoolName || this.post.author.name + '的项目',
        location: this.post.location || '未知位置',
        subject: this.post.subject || '未知科目',
        contact: this.applyForm.contact,
        message: this.applyForm.message,
        status: '待审核',
        createTime: new Date().toISOString()
      })
      
      uni.setStorageSync('applications', applications)
      
      // 显示成功提示
      uni.showToast({
        title: '申请已提交',
        icon: 'success'
      })
      
      // 重置表单并关闭弹窗
      this.applyForm = {
        contact: '',
        message: ''
      }
      this.showApply = false
    },
    sharePost(post) {
      uni.share({
        provider: "weixin",
        scene: "WXSceneSession",
        type: 0,
        title: "朋知云学 - 支教需求",
        summary: post.content,
        success: function() {
          uni.showToast({
            title: '分享成功',
            icon: 'success'
          })
        }
      })
    }
  },
  onShareAppMessage() {
    return {
      title: this.post.content.substring(0, 20) + '...',
      path: `/pages/post/detail?id=${this.post.id}`
    }
  }
}
</script>
